package com.lgx.authorize.module.rest;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.authorize.module.entity.ApplicationApplykeyInfo;
import com.lgx.authorize.module.service.IApplicationApplykeyInfoService;

/**
 * 
 * this rest contoller is support for appkey service.
 * @author pengdeyi (king)
 *
 */
@RequestMapping("/genapp")
@Controller
public class AuthorizeAppkeyController {
	
	@Autowired
	IApplicationApplykeyInfoService applicationApplykeyInfoService;
	
	public IApplicationApplykeyInfoService getApplicationApplykeyInfoService() {
		return applicationApplykeyInfoService;
	}

	/**
	 * this support to gen application key
	 * @param name
	 * @param timeLine
	 * @return
	 */
	@RequestMapping("/gen/name/{name}/t/{t}")
	@ResponseBody
	public Object genAppKey(@PathVariable("name") String name){
		if(StringUtils.isNotBlank(name)){
			ApplicationApplykeyInfo info = applicationApplykeyInfoService.findApplicationApplyKeyInfoByName(name);
			if(info!=null){
				return "errorMsg:this appname has been registed please change other one";
			}else{
				info = new ApplicationApplykeyInfo();
				info.setAppName(name);
				info.setAppkey(genKeyValue(info));
				info.setApplyTime(new Date());
				applicationApplykeyInfoService.createApplicationApplykeyInfo(info);
				return info.getAppkey();
			}
		}else{
			return "errorMsg:application name can't be null";
		}
	}
	
	/**
	 * this method support key
	 * @param applicationApplykeyInfo
	 * @return
	 */
	private String genKeyValue(ApplicationApplykeyInfo applicationApplykeyInfo){
		String key = "";
		if(applicationApplykeyInfo!=null&&
				StringUtils.isNotBlank(applicationApplykeyInfo.getAppName())){
			key = Long.toHexString(new Date().getTime());
		}
		return key;
	}
	
	@RequestMapping("/list")
	@ResponseBody
	public Object listAllAppkeys(){
		List<ApplicationApplykeyInfo> infos = applicationApplykeyInfoService.listAllApplicationApplykeyInfos();
		if(infos!=null&&infos.size()!=0){
			return infos;
		}else{
			return "errorMsg : no data find";
		}
	}
	
}
